<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="addBomProcess">新 增 </el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.productionorder_delete" :disabled="deleteLeft" @click="handleDelete('bom')"
          >删 除
        </el-button>
        <el-button type="primary" size="small" icon="el-icon-plus" @click="handleEnbale">启用</el-button>
        <el-button type="primary" size="small" icon="el-icon-plus" @click="handleDisbale">禁用</el-button>
      </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button type="text" icon="el-icon-view" size="small" plain style="border: 0; background-color: transparent !important" @click.stop="viewBomProcess(row)"
          >查看
        </el-button>
        <el-button
          type="text"
          icon="el-icon-edit"
          size="small"
          :disabled="row.status === 1"
          plain
          style="border: 0; background-color: transparent !important"
          @click.stop="editBomProcess(row)"
          >编辑
        </el-button>
      </template>
      <template slot-scope="{ row }" slot="status">
        <span>{{ row.status === 0 ? '禁用' : '启用' }}</span>
      </template>
    </avue-crud>
    <el-dialog append-to-body :close-on-click-modal="false" :title="title" :visible.sync="showDialog" v-if="showDialog" width="65%" top="5vh">
      <el-row :gutter="4">
        <el-col>
          <avue-form ref="properties" v-model="properties" :option="propertiesOption" @submit="submit"></avue-form>
        </el-col>
      </el-row>
      <el-row :gutter="4">
        <el-col :span="4">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>工序列表</span>
            </div>
            <div class="palette-list">
              <div class="palette-div" id="myPaletteDiv"></div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="20">
          <div>
            <el-card class="box-card" style="height: 33px">
              <div slot="header">
                <span>主料清单</span>
              </div>
            </el-card>
            <avue-crud
              ref="partMasterCrud"
              :option="partMasterOption"
              :table-loading="partMasterLoading"
              :data="partMasterData"
              :permission="permissionList"
              :before-open="beforeOpen"
              @row-save="rowPartMasterSave"
              @row-del="rowPartMasterDel"
              v-model="partMasterForm"
              @selection-change="selectionPartMasterChange"
              @row-click="rowPartMasterClick"
            >
              <template slot="menuLeft">
                <el-button type="primary" size="small" icon="el-icon-plus" @click="addCellRow('partMasterData')" v-if="!(title === '查看')" :disabled="!processParams.processId"
                  >新增</el-button
                >
                <el-button type="primary" size="small" icon="el-icon-plus" @click="savePart('partMaster')" v-if="!(title === '查看')" :disabled="!saveBtnFlag">保存</el-button>
                <el-button type="danger" size="small" icon="el-icon-delete" @click="handleDelete('partMaster')" v-if="!(title === '查看')" :disabled="!processParams.processId"
                  >删 除
                </el-button>
              </template>
            </avue-crud>
          </div>
          <div>
            <el-card class="box-card" style="height: 33px">
              <div slot="header">
                <span>替代料清单</span>
              </div>
            </el-card>
            <avue-crud
              ref="replacePartCrud"
              :option="replacePartOption"
              :table-loading="replacePartLoading"
              :data="replacePartData"
              :permission="permissionList"
              :before-open="beforeOpen"
              @row-del="rowReplacePartDel"
              v-model="replacePartForm"
              @selection-change="selectionReplacePartChange"
              @row-click="rowReplacePartClick"
            >
              <template slot="menuLeft">
                <el-button type="primary" size="small" icon="el-icon-plus" v-if="bomDetailId && title !== '查看'" @click="addCellRow('replacePartData')">新增</el-button>
                <el-button type="primary" size="small" icon="el-icon-plus" v-if="bomDetailId && title !== '查看'" @click="savePart()" :disabled="!saveBtnFlag2">保存</el-button>
                <el-button type="danger" size="small" icon="el-icon-delete" v-if="bomDetailId && title !== '查看'" @click="handleDelete('replacePart')">删 除 </el-button>
              </template>
            </avue-crud>
          </div>
        </el-col>
      </el-row>
      <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  add,
  update,
  remove,
  disable,
  enable,
  getProcessList,
  addPart,
  getPartList,
  removePart,
  addReplace,
  removeReplace,
  getReplaceList
} from '@/api/admin/productionbom';
import { getOption, getPropertiesOption, getPartMasterOption, getReplacePartOption } from './productionbom';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { mapGetters } from 'vuex';
import { go } from '@/assets/js/go';
import { guid } from '@/util/helpers';
let G = go.GraphObject.make; //GOJS对象
//!processParams.processId &&
export default {
  components: {
    CommonModalTemplate
  },
  data() {
    return {
      form: {},
      bomId: '',
      paletteData: [], //左侧控件数据
      sourceBomId: '',
      index: -1,
      bomDetailId: '',
      partId: '', //主物料Id
      productionId: '', //产品Id
      processParams: {},
      partMasterForm: {},
      replacePartForm: {},
      properties: {},
      isNone: '',
      timer: new Date().getTime(),
      query: {},
      loading: true,
      partMasterLoading: false,
      replacePartLoading: false,
      title: '',
      showDialog: false,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      processParam: {},
      selectionList: [],
      selectionPartMasterList: [],
      selectionReplacePartList: [],
      tableOption: {},
      option: getOption(),
      propertiesOption: getPropertiesOption(this),
      partMasterOption: getPartMasterOption(this),
      replacePartOption: getReplacePartOption(this),
      data: [],
      partMasterData: [],
      replacePartData: [],
      workProcessList: [] //工序列表
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      console.log(this.permission);
      return {
        addBtn: this.vaildData(this.permission.productionbom_add, false),
        viewBtn: this.vaildData(this.permission.productionbom_view, false),
        delBtn: this.vaildData(this.permission.productionbom_delete, false),
        editBtn: this.vaildData(this.permission.productionbom_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    deleteLeft() {
      if (this.selectionList.length !== 0) {
        return this.selectionList.every((item, index) => {
          return item.status == 1;
        });
      }
      return true;
    },
    saveBtnFlag() {
      if (this.partMasterData.length !== 0) {
        return this.partMasterData.some((item, idx) => {
          return item.$cellEdit;
        });
      } else {
        return false;
      }
    },
    saveBtnFlag2() {
      if (this.replacePartData.length !== 0) {
        return this.replacePartData.some((item, idx) => {
          return item.$cellEdit;
        });
      } else {
        return false;
      }
    },
    partMasterIds() {
      let ids = [];
      this.selectionPartMasterList.forEach((ele) => {
        ids.push(ele.bomDetailId);
      });
      return ids.join(',');
    },
    replacePartIds() {
      let ids = [];
      this.selectionReplacePartList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {},
  methods: {
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowPartMasterSave(row, done, loading) {},
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    rowPartMasterDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return removePart(row.id);
        })
        .then(() => {
          this.onPartMasterLoad({
            bomId: this.bomId,
            processId: this.processParams.processId,
            routeType: this.processParams.routeType,
            parentId: 0
          });
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    rowReplacePartDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return removeReplace(row.id);
        })
        .then(() => {
          this.onReplacePartLoad();
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete(title) {
      if (this.selectionList.length === 0 && title === 'bom') {
        this.$message.warning('请选择至少一条数据');
        return;
      }

      if (this.selectionList.length > 1 && title === 'bom') {
        this.$message.warning('只能选择一条数据进行删除');
        return;
      }
      if (this.selectionPartMasterList.length === 0 && title === 'partMaster') {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      if (this.selectionReplacePartList.length === 0 && title === 'replacePart') {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          if (title === 'bom') {
            return remove(this.ids);
          } else if (title === 'partMaster') {
            let delItem = this._find(this.partMasterData, ['$cellEdit', true]);
            return !delItem ? removePart(this.partMasterIds) : this._remove(this.partMasterData, delItem);
          } else {
            let delItem = this._find(this.replacePartData, ['$cellEdit', true]);
            return !delItem ? removeReplace(this.replacePartIds) : this._remove(this.replacePartData, delItem);
          }
        })
        .then(() => {
          if (title === 'bom') {
            this.onLoad(this.page);
          } else if (title === 'partMaster') {
            this.replacePartData = [];
            this.onPartMasterLoad({
              bomId: this.bomId,
              processId: this.processParams.processId,
              routeType: this.processParams.routeType,
              parentId: 0
            });
          } else {
            this.onReplacePartLoad();
          }
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionPartMasterChange(list) {
      this.selectionPartMasterList = list;
    },
    selectionReplacePartChange(list) {
      this.selectionReplacePartList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      params['sourceType'] = 'MES';
      params['isAll'] = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    onPartMasterLoad(data) {
      this.partMasterLoading = true;
      this.bomId &&
        getPartList({
          bomId: this.bomId,
          processId: data.processId,
          routeCode: this.processParams.routeCode
        }).then((res) => {
          this.partMasterData = res.data.data.records;
          this.partMasterLoading = false;
        });
    },
    onReplacePartLoad() {
      this.replacePartLoading = true;
      getReplaceList({
        bomDetailId: this.bomDetailId,
        bomId: this.bomId
      }).then((res) => {
        this.replacePartData = res.data.data || [];
        this.replacePartLoading = false;
      });
    },

    /**
     * 新增
     */
    addBomProcess() {
      this.resetForm();
      this.properties = {};
      this.bomId = '';
      this.bomDetailId = '';
      this.title = '新增';
      this.$set(this.properties, 'createTime', this.$moment().format('yyyy-MM-DD HH:mm:ss'));
      this.changeAddEditOption();
      this.showDialog = true;
    },
    /**
     * 编辑
     */
    editBomProcess(row) {
      this.resetForm();
      this.bomId = '';
      this.bomDetailId = '';
      this.processParams = {};
      this.title = '修改';
      this.changeAddEditOption();
      this.showDialog = true;
      this.sourceBomId = row.sourceBomId;
      this.getBomForm(row);
      this.initProcessData({ partNo: row.partNo });
    },
    /**
     * 查看
     */
    viewBomProcess(row) {
      this.bomId = '';
      this.bomDetailId = '';
      this.processParams = {};
      this.resetForm();
      this.title = '查看';
      this.changeViewOption();
      this.showDialog = true;
      this.bomId = row.id;
      this.sourceBomId = row.sourceBomId;
      this.getBomForm(row);
      this.initProcessData({ partNo: row.partNo });
    },
    /**
     * 保存主料清单
     */
    savePart(title) {
      if (!this.bomId) {
        this.$message({
          type: 'warning',
          message: '请先点击保存!'
        });
        return;
      }
      if (title === 'partMaster') {
        this.$refs.partMasterCrud.validateCellForm().then((res) => {
          if (Object.keys(res).length === 0) {
            let idx;
            this.title === '新增' ? (idx = 0) : (idx = this.index);
            this.partMasterData[idx]['bomId'] = this.bomId;
            this.partMasterData[idx]['processId'] = this.processParams.processId;
            this.partMasterData[idx]['routeType'] = this.processParams.routeType;
            this.partMasterData[idx]['routeCode'] = this.processParams.routeCode;
            this.partMasterData[idx]['sourceType'] = 'MES';
            addPart(this.partMasterData[idx]).then((res) => {
              this.onPartMasterLoad({
                bomId: this.bomId,
                processId: this.processParams.processId,
                routeType: this.processParams.routeType,
                routeCode: this.processParams.routeCode,
                parentId: 0
              });
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
            });
          }
        });
      } else {
        this.$refs.replacePartCrud.validateCellForm().then((res) => {
          if (Object.keys(res).length === 0) {
            let idx;
            this.title === '新增' ? (idx = 0) : (idx = this.index);
            this.replacePartData[idx]['bomDetailId'] = this.bomDetailId;
            addReplace(this.replacePartData[idx]).then((res) => {
              this.onReplacePartLoad();
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
            });
          }
        });
      }
    },
    /**
     * 添加物料
     */
    addCellRow(data) {
      if (!this.bomId) {
        this.$message({
          type: 'warning',
          message: '请选点击保存!'
        });
        return;
      }
      if (this.isRowAdd(data)) {
        if (data === 'partMasterData') {
          this[data].unshift({
            $cellEdit: true,
            isKeyPart: false,
            name: '',
            partModel: '',
            partNo: '',
            unitQty: ''
          });
        } else {
          this[data].unshift({
            $cellEdit: true,
            isKeyPart: false,
            partName: '',
            partModel: '',
            partNo: '',
            unitQty: ''
          });
        }
      }
    },
    /**
     * 是否添加行编辑
     */
    isRowAdd(data) {
      return this[data].every((item, index) => {
        if (!this._get(this[data][index], '$cellEdit', false)) {
          return item.partNo;
        }
      });
    },

    /**
     * 判断是否有物料未进行保存
     */
    checkMaterialSave(data) {
      return this[data].some((item, index) => {
        if (this._get(this[data][index], '$cellEdit', false)) {
          return item.partNo;
        }
      });
    },
    /**
     * 启用
     */
    handleEnbale() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('是否启用?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return enable(this.selectionList[0].id, this.selectionList[0].partMasterId);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    /**
     * 禁用
     */
    handleDisbale() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('是否禁用?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return disable(this.selectionList[0].id, this.selectionList[0].partMasterId);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    submit() {
      this.$refs.properties.validate((valid, done) => {
        if (valid) {
          let paramsMap = {
            id: this.properties['id'],
            partMasterId: this.properties['partMasterId'],
            sourceBomId: this._get(this.properties, 'sourceBomId', ''),
            creator: this._get(this.properties, 'creator', ''),
            createTime: this._get(this.properties, 'createTime', ''),
            bomNo: this.properties['partNo'],
            bomVersion: this.properties['bomVersion'],
            sourceType: 'MES',
            partNo: this.properties['partNo']
          };
          add(paramsMap).then(
            (res) => {
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              this.bomId = res.data.data;
              this.changeViewOption();
              this.refreshChange();
            },
            (error) => {
              window.console.log(error);
            }
          );
          done();
        } else {
          console.log('error submit!!');
          return false;
        }
      });

      this.initProcessData({
        partNo: this.properties['partNo']
      });
    },
    reset() {},
    getSelectedRows(rowData, titleInfo) {
      if (titleInfo === 'keyPart') {
        let flag = this.isRepeatPart(this.partMasterData, rowData, 'partNo');
        if (!flag) {
          return;
        }
        const idx = this.index;
        // this.productionId = rowData.id;
        this.partMasterData[idx]['prePartMasterFlag'] = rowData.prePartMasterFlag;
        this.partMasterData[idx]['unitQty'] = rowData.unitQty;
        this.partMasterData[idx]['partMasterId'] = rowData.id;
        this.partMasterData[idx]['partName'] = rowData.name;
        this.$set(this.partMasterData[idx], 'partNo', rowData.partNo);
        this.$set(this.partMasterData[idx], 'name', rowData.name);
        this.$set(this.partMasterData[idx], 'partModel', rowData.partModel);
        this.$set(this.partMasterData[idx], 'isKeyPart', rowData.isKeyPart);
      } else if (titleInfo === 'replacePart') {
        const idx = this.index;
        this.replacePartData[idx]['unitQty'] = rowData.unitQty;
        this.replacePartData[idx]['partMasterId'] = rowData.partMasterId;
        this.$set(this.replacePartData[idx], 'partNo', rowData.partNo);
        this.$set(this.replacePartData[idx], 'partName', rowData.partName);
        this.$set(this.replacePartData[idx], 'partModel', rowData.partModel);
      } else {
        this.productionId = rowData.id;
        this.$set(this.properties, 'partMasterId', rowData.id);
        this.properties['sourceBomId'] = rowData.sourceBomId;
        this.properties['partNo'] = rowData.partNo;
        this.properties['partName'] = rowData.name;
        this.properties['bomVersion'] = rowData.bomVersion;
        this.properties['creator'] = rowData.creator;
        this.initProcessData({
          partNo: rowData.partNo
        });
      }
    },

    /**
     * 判断物料数据是否有相同
     */
    isRepeatPart(arr, obj, attr) {
      let flag = this._some(arr, (item) => {
        return item[attr] === obj[attr];
      });

      if (flag) {
        this.$message({
          type: 'warning',
          message: '选择的物料与已选的物料有重复,请重新选择'
        });
        return false;
      }
      return true;
    },
    rowPartMasterClick(row) {
      this.bomDetailId = row.bomDetailId;
      this.partId = row.id;
      this.index = row.$index;
      this.bomDetailId && this.onReplacePartLoad();
    },
    rowReplacePartClick(row) {
      this.index = row.$index;
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    /**获取bom表单数据 */
    getBomForm(data) {
      this.productionId = data.partMasterId;
      this.properties['id'] = data.id;
      this.properties['partNo'] = data.partNo;
      this.properties['partMasterId'] = data.partMasterId;
      this.properties['partName'] = data.partName;
      this.properties['sourceBomId'] = data.sourceBomId;
      this.properties['bomVersion'] = data.bomVersion;
      this.properties['creator'] = data.creator;
      this.properties['createTime'] = data.createTime;
    },

    async initProcessData(params) {
      let that = this;
      // 获取工序信息
      let result = await getProcessList(params);
      if (result && result.status == 200) {
        let data = result.data.data;
        that.paletteData = data;
        for (let i = 0; i < that.paletteData.length; i++) {
          that.paletteData[i].category = that.paletteData[i].id;
          that.paletteData[i].key = guid();
          that.paletteData[i].code = that.paletteData[i].code;
          that.paletteData[i].routeType = that.paletteData[i].type;
          that.paletteData[i].text = that.paletteData[i].name;
          that.paletteData[i].name = that.paletteData[i].name;
          that.paletteData[i].imgsrc = that.paletteData[i].imgsrc;
        }
        that.initLeftStations('myPaletteDiv', that.paletteData); //  初始化左侧工站库
      }
    },

    //  初始化左侧工序
    initLeftStations(div, myPaletteData) {
      let myPalette = G(go.Palette, div, {
        layout: G(go.GridLayout, {
          sorting: go.GridLayout.Forward,
          cellSize: new go.Size(1, 1),
          wrappingColumn: 2, // 工站库列数
          isViewportSized: true
        })
      });
      for (var i = 0; i < this.paletteData.length; i++) {
        myPalette.nodeTemplateMap.add(
          this.paletteData[i].category,
          this.makeNodeTemplate(this.paletteData[i].imgsrc || '@/assets/img/order-route/conveyor_blue.png', this.paletteData[i])
        );
      }
      myPalette.model.nodeDataArray = this.paletteData;
      myPalette.nodes.each(function (node) {
        node.ports.each(function (port) {
          port.cursor = '';
        });
        node.elements.each(function (tb) {
          if (tb instanceof go.TextBlock) {
            tb.visible = true;
          }
        });
      });
    },

    //创建拖拽模板
    makeNodeTemplate(imgsrc, data) {
      return G(
        go.Node,
        'Vertical',
        {
          locationSpot: go.Spot.Center
        },
        new go.Binding('location', 'location', go.Point.parse).makeTwoWay(go.Point.stringify),
        {
          selectable: true,
          selectionAdornmentTemplate: this.makeNodeSelectionAdornmentTemplate(),
          click: (e, node) => {
            //点击工序
            if (!this.bomId) {
              this.$message({
                type: 'warning',
                message: '请先点击保存!'
              });
              return;
            }

            if (this.checkMaterialSave('partMasterData')) {
              this.$message({
                type: 'warning',
                message: '还有物料未进行保存'
              });
              return;
            }
            this.processParams = {
              processId: data.id,
              routeType: data.routeType,
              routeCode: data.code
            };
            this.partMasterData = [];
            this.replacePartData = [];
            this.onPartMasterLoad(this.processParams);
          }
        },
        G(go.Picture, imgsrc, {
          width: 45,
          height: 40,
          margin: 2,
          portId: '',
          toMaxLinks: 1,
          fromMaxLinks: 1,
          cursor: 'pointer'
        }),
        G(
          go.TextBlock,
          '默认文本',
          {
            editable: false,
            margin: 0,
            textAlign: 'center',
            width: 40,
            maxLines: 3,
            overflow: go.TextBlock.OverflowEllipsis,
            alignment: go.Spot.Center
          },
          new go.Binding('text', 'text')
        ),
        {
          toolTip: this.makeTooltipTemplate(),
          contextMenu: {}
        }
      );
    },
    // 选中节点的样式
    makeNodeSelectionAdornmentTemplate() {
      return G(
        go.Adornment,
        'Auto',
        G(go.Shape, {
          fill: null,
          stroke: 'deepskyblue',
          strokeWidth: 2,
          strokeDashArray: [4, 2]
        }),
        G(go.Placeholder)
      );
    },
    // 悬浮在某一个图标上提示信息/tooltip上显示的信息
    makeTooltipTemplate() {
      return G(
        go.Adornment,
        go.Panel.Auto,
        G(go.Shape, 'RoundedRectangle', {
          fill: 'whitesmoke',
          stroke: 'gray'
        }),
        G(
          go.TextBlock,
          {
            margin: 5,
            editable: true
          },
          new go.Binding('text', '', function (data) {
            if (data.text !== undefined) return data.text;
            return '(未命名)';
          })
        )
      );
    },
    resetForm() {
      this.partMasterData = [];
      this.replacePartData = [];
    },
    /**
     * 改变查看配置
     */
    changeViewOption() {
      this.propertiesOption.submitBtn = false;
      this.propertiesOption.column[0].disabled = true;
      this.propertiesOption.column[2].disabled = true;
      // this.partMasterOption.menu = false;
      // this.replacePartOption.menu = false;
    },
    /**
     * 改变新增和编辑配置
     */
    changeAddEditOption() {
      this.title === '新增' ? (this.propertiesOption.column[0].disabled = false) : (this.propertiesOption.column[0].disabled = true);
      this.propertiesOption.submitBtn = true;
      this.propertiesOption.column[2].disabled = false;
      // this.partMasterOption.menu = true;
      // this.replacePartOption.menu = true;
    },
    /**
     * 选择关键料模态框
     */
    openKeyPartModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择主料信息（双击进行选择）',
        url: `/api/mes-admin/bom/detail/part-page?bomId=${this.sourceBomId}&partMasterId=${this.productionId}`,
        isPage: true,
        index: false,
        selection: true,
        // noPageParams: true,
        // filterOption: {
        //   isFilter: true,
        //   prop: 'name',
        //   data: this.partMasterData.map((item) => item.name)
        // },
        rowSelectionType: 'single',
        titleInfo: 'keyPart',
        columnDefs: [
          {
            label: '类型',
            prop: 'categoryId',
            type: 'tree',
            dicUrl: '/api/mes-admin/part-category/tree',
            props: {
              label: 'title',
              value: 'id'
            }
          },
          {
            label: '编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '型号',
            prop: 'partModel'
          },
          {
            label: '描述',
            prop: 'description'
          }
        ]
      };
    },
    /**
     * 选择替代料模态框
     */
    openRepalcePartModal(partType) {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择替代料信息（双击进行选择）',
        url: `/api/mes-admin/bom/detail/erp/replace/list?partId=${this.partId}&bomId=${this.sourceBomId}`,
        isPage: true,
        index: false,
        selection: true,
        // noPageParams: true,
        // filterOption: {
        //   isFilter: true,
        //   prop: 'partName',
        //   data: this.replacePartData.map((item) => item.partName)
        // },
        rowSelectionType: 'single',
        titleInfo: partType,
        columnDefs: [
          {
            label: '编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '名称',
            prop: 'partName',
            search: true
          },
          {
            label: '型号',
            prop: 'partModel'
          },
          {
            label: '描述',
            prop: 'description'
          }
        ]
      };
    },

    /**
     * 选择产品模态框
     */
    openProductModal(partType) {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择产品信息（双击进行选择）',
        url: `/api/mes-admin/part-master/page?semifinished=true`,
        isPage: true,
        index: false,
        selection: true,
        rowSelectionType: 'single',
        titleInfo: partType,
        columnDefs: [
          {
            label: '类型',
            prop: 'categoryId',
            search: true,
            type: 'tree',
            dicUrl: '/api/mes-admin/part-category/tree',
            props: {
              label: 'title',
              value: 'id'
            }
          },
          {
            label: '编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '型号',
            prop: 'partModel'
          },
          {
            label: '描述',
            prop: 'description'
          },
          {
            label: '版本',
            prop: 'revision'
          }
        ]
      };
    }
  }
};
</script>

<style lang="scss" scoped>
.palette-list {
  height: calc(100vh - 40vh);
  .palette-div {
    width: 100%;
    height: 100%;
  }
}

.title {
  font-size: 14px;
  padding: 5px;
  background-color: #eee;
}
.btn {
  width: 50px;
}
</style>
